#include "Thread.hpp"

const int num = 10;

void *ThreadFunc(void *args)
{
    sleep(1);
    std::string name = static_cast<const char *>(args);
    int cnt = 5;
    while (cnt--)
    {
        std::cout << name << "运行中..." << std::endl;
        sleep(1);
    }
    return nullptr;
}

int main()
{
    std::vector<long long> tids;

    for (int i = 0; i < num; i++) // 创建10个线程
    {
        //char name[64]; //错误写法
        char* name = new char[64]; //正确写法,堆区开辟空间
        snprintf(name, 64, "新线程%d", i); // 格式化名字
        pthread_t tid;
        int n = pthread_create(&tid, nullptr, ThreadFunc, name);
        if (n == 0)
            tids.push_back(tid); // 创建成功就把新线程的ID存着
        else
            continue;
    }

    for (int i = 0; i < num; i++) //一个一个等待
    {
        int n = pthread_join(tids[i], nullptr);
        if (n == 0)
            std::cout << "等待成功" << std::endl;
        else
            std::cout << "等待失败" << std::endl;
    }

    return 0;
}
